package com.lee.demo1.business;


import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.lee.demo1.dao.SysMenuMapper;
import com.lee.demo1.dao.SysRoleMapper;
import com.lee.demo1.dao.SysRoleMenuMapper;
import com.lee.demo1.dao.SysUserMapper;
import com.lee.demo1.domain.SysMenu;
import com.lee.demo1.domain.SysRole;
import com.lee.demo1.domain.SysRoleMenuKey;
import com.lee.demo1.domain.SysUser;


/**
 * 用户管理
 * @author leopad
 *
 */
@Service
public class SysUserBusiness {
	
	@Resource
	private SysUserMapper sysUserMapper;
	
	@Resource
	private SysRoleMapper sysRoleMapper;
	
	@Resource
	private SysMenuMapper sysMenuMapper;
	
	@Resource
	private SysRoleMenuMapper sysRoleMenuMapper;
	
	public void updateRoleMenu(Integer sysRoleId , String checkedMenuIds){
		
		String[] ckIds = StringUtils.split(checkedMenuIds, ",");
		
		sysRoleMenuMapper.deleteBySysRoleId(sysRoleId);
		
		for(String menuId : ckIds){
			Integer mId = Integer.parseInt(menuId);
			SysRoleMenuKey record = new SysRoleMenuKey();
			record.setSysRoleId(sysRoleId);
			record.setSysMenuId(mId);
			sysRoleMenuMapper.insert(record);
		}
		
	}
	/**
	 * 根据用户名密码查询是否存在此用户，用于登录验证时使用。
	 * @param sysUser
	 * @return
	 */
	public SysUser getSysUserByNameAndPassword(SysUser sysUser){
		return sysUserMapper.selectByNameAndPassword(sysUser);
	}
	/**
	 * 更新用户最后登录时间和IP
	 * @param id
	 * @param ip
	 * @return
	 */
	public int updateLastLoginTimeAndIP(int id,String ip){
		SysUser user = new SysUser();
		user.setId(id);
		user.setLastLoginIp(ip);
		user.setLastLoginTime(new Date());
		return sysUserMapper.updateByPrimaryKeySelective(user);
	}
	
	/**
	 * 修改系统用户
	 * @param sysUser
	 * @return
	 */
	public int updateSysUser(SysUser sysUser){
		return sysUserMapper.updateByPrimaryKeySelective(sysUser);
	}
	
	
	public List<SysRole> getRoles(){
		return sysRoleMapper.selectAll();
	}
	
	
	public List<SysMenu> getMenus(){
		return sysMenuMapper.selectAll();
	}
	
	public List<SysRoleMenuKey> getRoleMenus(Integer sysRoleId){
		return sysRoleMenuMapper.selectRoleMenuByRoleId(sysRoleId);
	}
}
